// 当前地址完整协议 + 域名 + 端口
import store from "@/store";
import request from '@/utils/request'
import { EventBus } from '@/views/youshuda/utils/event-bus';

let origin = ''

/**
 * 添加来自父窗口的获取数据请求监听
 */
export function addMessageListener() {
  try {
    const parsedUrl = new URL(window.location.href); // 创建URL对象
    origin = parsedUrl['origin']
  } catch (error) {
    origin = "*"
  }
  // 监听来自父窗口的获取数据请求
  window.addEventListener('message', (event) => {
    //移动端appKey
    let appKeyList =[];
    if(!localStorage.getItem('appKeyList')){
      getAllAppKey();
      //appKeyList = localStorage.getItem('appKeyList').split(',');
    }else{
      appKeyList = localStorage.getItem('appKeyList').split(',');
    }
    // 验证来源，替换为父页面域名
    if (event.origin !== origin && appKeyList.indexOf(event.data.key) === -1) return;
    if (event.data.type === 'GET_VUEX_DATA') {
      postMessageToParent();
    }
    if (event.data.type === 'SET_BUILD_MODE') {
      store.dispatch('changeSysAiBuildMode', {'mode': 'AiBuild'})
    }
    /** uni-app 消息接收*/
    if (event.data.type === 'UNI-APP-SEND') {
      //触发时间监听
      EventBus.$emit(event.data.busName, event.data.data)
    }

  })
}

/**
 * 向父窗口发送消息
 */
export function postMessageToParent() {
  try{
    let data = {
      "menuInfo": store.getters.Sys_AiBuild_MenuInfo.map(item => item.meta)
    }
    if(data){
      window.parent.postMessage({
        type: 'VUEX_DATA_RESPONSE',
        payload: data
      }, origin)
    }
  }catch (e){}
}

/** 获取平台所有的appKey*/
export function getAllAppKey() {
  request({
    url: '/generator/AppBuildInfo/getAllAppKey',
    method: 'get'
  }).then(res => {
    if (res.code == 200) {
      localStorage.setItem("appKeyList", res.data)
    }
  })
}
